package com.yizisu.playerlibrary.view.video_view.view

import android.content.Context
import android.util.AttributeSet
import android.webkit.URLUtil
import androidx.appcompat.widget.AppCompatImageView
import com.yizisu.playerlibrary.IYzsPlayer
import com.yizisu.playerlibrary.impl.exoplayer.PlayerPlaybackState
import com.yizisu.playerlibrary.service.download.PlayerDownload
import com.yizisu.playerlibrary.view.video_view.helper.IPlayerConfig
import com.yizisu.playerlibrary.view.video_view.helper.IPlayerHelper

/**
 * 缓存按钮
 */
open class PlayerCacheView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : AppCompatImageView(
    context,
    attrs,
    defStyleAttr
), IPlayerHelper {
    private var playerConfig: IPlayerConfig? = null
    override fun onAttachPlayerConfig(playerConfig: IPlayerConfig) {
        super.onAttachPlayerConfig(playerConfig)
        this.playerConfig = playerConfig
        visibility = INVISIBLE
        setOnClickListener {
            onClick(playerConfig)
        }
        if (drawable == null) {
            setImageResource(android.R.drawable.stat_sys_download_done)
        }
    }

    var canDownload: Boolean? = null

    init {
        visibility = INVISIBLE
    }


    override fun onPlaybackStateChanged(state: PlayerPlaybackState) {
        super.onPlaybackStateChanged(state)
        if (canDownload == null && state == PlayerPlaybackState.STATE_READY
            && URLUtil.isNetworkUrl(playerConfig?.player?.getCurrentModel()?.mediaItem?.playbackProperties?.uri?.toString())
        ) {
            canDownload = true
        }
    }

    override fun onPrepare(playerModel: IYzsPlayer.Model?) {
        super.onPrepare(playerModel)
        visibility = INVISIBLE
        canDownload = null
    }

    override fun onError(throwable: Throwable, playerModel: IYzsPlayer.Model?) {
        super.onError(throwable, playerModel)
        visibility = INVISIBLE
        canDownload = false
    }

    override fun isNeedPlayerListener(): Boolean {
        return true
    }

    open fun onClick(playerConfig: IPlayerConfig) {
        if (PlayerDownload.onInterceptCacheClickListener?.invoke(this, playerConfig) != true) {
            playerConfig.player?.getCurrentModel()?.mediaItem?.playbackProperties?.uri?.let { uri ->
                PlayerDownload.startOrResumeDownload(uri.toString(), uri)
            }
        }
    }
}